package com.virtualtrainer_01.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.virtualtrainer_01.model.Food;
import com.virtualtrainer_01.model.Model;

public class FoodDB extends SQLiteDB {
	public static final String KEY_ID = "_id";
	public static final String KEY_NAME = "name";
	public static final String KEY_DESCRIPTION = "description";
	public static final String KEY_CALORIES = "calories";
	private static final String DATABASE_TABLE = "food";

	public FoodDB(Context c) {
		super(c, DATABASE_TABLE);
	}

	@Override
	public String getData() {
		String[] columns = new String[] { KEY_ID, KEY_NAME, KEY_DESCRIPTION,
				KEY_CALORIES };
		Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
				null, null);
		String result = "";

		int iRow = c.getColumnIndex(KEY_ID);
		int iName = c.getColumnIndex(KEY_NAME);
		int iDescr = c.getColumnIndex(KEY_DESCRIPTION);
		int iCalories = c.getColumnIndex(KEY_CALORIES);

		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
			result = result + c.getString(iRow) + " " + c.getString(iName)
					+ " " + c.getString(iDescr) + " " + c.getString(iCalories);
		return result;
	}

	@Override
	public long createEntry(Model entry) {
		Food f = (Food) entry;
		ContentValues cv = new ContentValues();
		cv.put(KEY_NAME, f.getName());
		cv.put(KEY_CALORIES, f.getCalories());
		cv.put(KEY_DESCRIPTION, f.getDescription());
		return ourDatabase.insert(DATABASE_TABLE, null, cv);
	}
	
	public Food getFood(int id)
	{
		String sql = "SELECT * FROM "+DATABASE_TABLE+" t where t."+KEY_ID+"="+"'"+id+"';";
		Cursor c = ourDatabase.rawQuery(sql, null); 
		
		int iName = c.getColumnIndex(KEY_NAME);
		int iCalories = c.getColumnIndex(KEY_CALORIES);
		int iDescr = c.getColumnIndex(KEY_DESCRIPTION);

		Food f = new Food();
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
		{
			f.setName(c.getString(iName));
			f.setCalories(Double.parseDouble(c.getString(iCalories)));			
			f.setDescription(c.getString(iDescr));
		}
		return f;
	}
}
